package xiongguanweb

import org.slf4j.Logger
import org.slf4j.LoggerFactory

class LoginInterceptor {
    def userService

    LoginInterceptor() {
        match(controller: "user").excludes(action: "notifyGasRecharge")
                .excludes(action: "checkVerifyCode")
                .excludes(action: "userRegister")
                .excludes(action: "resetLoginpass")
                .excludes(action: "verifyCode")
                .excludes(action: "userRegisterSaveInfo")
    }

    private static Logger logger = LoggerFactory.getLogger(LoginInterceptor.class)

    boolean before() {
        logger.info("登录拦截器进入...")
        TreeMap<String, String> paras = new TreeMap<>()
        StringBuffer data = new StringBuffer()
        Enumeration enu = request.getParameterNames()
        while (enu.hasMoreElements()) {
            String paraName = (String) enu.nextElement()
            request.getParameter(paraName);
            paras.put(paraName, request.getParameter(paraName))
        }
        Iterator it = paras.keySet().iterator()
        while (it.hasNext()) {
            data.append(paras.get(it.next()))
        }
        logger.info("请求data===" + data.toString())
        // AND UNICODE(SUBSTRING((SELECT ISNULL(CAST(TYPE_NAME(SecurityChk..syscolumns.xtype) AS NVARCHAR(4000)),CHAR(32)) FROM SecurityChk..syscolumns,SecurityChk..sysobjects WHERE SecurityChk..syscolumns.name=CHAR(86)+CHAR(67)+CHAR(95)+CHAR(70)+CHAR(108)+CHAR(111)+CHAR(111)+CHAR(114) AND SecurityChk..syscolumns.id=SecurityChk..sysobjects.id AND SecurityChk..sysobjects.name=CHAR(84)+CHAR(98)+CHAR(95)+CHAR(85)+CHAR(115)+CHAR(101)+CHAR(114)+CHAR(73)+CHAR(110)+CHAR(102)+CHAR(111)),6,1)

        if (session.username == null) {
            redirect(url: '/login')
        } else {
            session.setMaxInactiveInterval(15 * 60)
//            if(data.contains("(") || data.contains("SELECT") || data.contains("slelect")){
//                return false
//            }else {
//                return true
//            }
            return sqlValidate(data.toString())
        }
    }

    boolean after() { true }

    void afterView() {
        // no-op
    }

    protected boolean sqlValidate(String str) {
        str = str.toLowerCase()// 统一转为小写
        str.replaceAll("--", "——")
        str.replaceAll("'", "’")
        String badStr = "exec|execute|insert|select|delete|update|master|truncate|javascript|count(*)|declare|create"// 过滤掉的sql关键字，可以手动添加
        String[] badStrs = badStr.split("\\|")
        for (int i = 0; i < badStrs.length; i++) {
            if (str.indexOf(badStrs[i].toLowerCase()) >= 0) {
                return false
            }
        }
        return true
    }
}
